package assignment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.xml.bind.JAXBException;

import assignment.jaxb.Card;
import assignment.jaxb.Cards;

/**
 * @author $Author:$
 * @version $Id: $
 */
public class SearchXML {

	public static void main(String[] args) throws MalformedURLException, IOException, JAXBException {
		
		// Define the URL source of the website to perform screen scrapping
		//String baseUrl = "http://www.gpureview.com/"; //if site is on-line
		//String urlSuffix = "search.php?query=Voodoo";
		
		// Alternative URL for off-line testing
		String baseUrl = "file:./site/"; //if site is off-line
		String urlSuffix = "search.php";
		
		// Define the fetcher and parser objects
		UrlFetcher fetcher = new UrlFetcher();
		GPUReviewParser parser = new GPUReviewParser(baseUrl);
		
		// Retrieve the list of graphic cards
		Cards card_list = parser.parseMasterPage(fetcher.get(baseUrl + urlSuffix));
		
		// Retrieve the details for each graphic card retrieved in the previous step
		for(Card card: card_list.getCards())
			parser.parseDetailPage(fetcher.get(card.getUrl()), card);
		
		// We will write the xml to this file
		File outXmlFile = new File("cards.xml");
		
		//using UTF-8
		XMLOutputter out = new XMLOutputter(new FileOutputStream(outXmlFile),"UTF-8"); 
		
		// schemaLocation will easy validation from within IDEs
		out.addSchemaLocation("http://dei.uc.pt/eai/assignment1","assignment1.xsd");
		
		System.out.println("Writting: "+outXmlFile.getCanonicalPath());
		out.writeFragment(); //writing "<?xml...?>"
		out.writeXSLTTemplateReference("cards.xsl"); //writing "<?xml-stylesheet...?>"
		out.write(card_list,true); // writing the actual xml content
		
		System.out.println("Success!");
	}
}
